<template>
  <div ref="mapContainer" class="map-container" />
</template>

<script setup>
import { ref, onMounted, onUnmounted } from "vue";
import { useMap } from "@/hooks/useMap";
import { useMarkers } from "@/hooks/useMarkers";
const mapContainer = ref();
// 使用地图hooks
const { map, initMap } = useMap(mapContainer, {
  tileType: "gaode",
  tileOptions: { type: "vector", layerOptions: {} }
});

// 定义props
const props = defineProps({
  center: {
    type: Array,
    default: () => [39.90923, 116.397428]
  },
  zoom: {
    type: Number,
    default: 13
  }
});
// 初始化标记管理hooks
const {
  addMarker,
  addCircle,
  addPolygon,
  handleMapClick,
  clearAll,
  destroy: destroyMarkers
} = useMarkers(map, {
  cluster: false,
  defaultCircleConfig: {
    color: "red",
    fillColor: "#f03",
    fillOpacity: 0.5,
    radius: 500
  }
});
onMounted(async () => {
  await initMap();
  // 初始化地图元素
  initMapElements();
});

onUnmounted(() => {
  // 清理地图实例
  if (map.value) {
    map.value.remove();
  }
});

// 封装地图元素初始化方法
const initMapElements = () => {
  // 添加默认标记
  addMarker({
    lat: props.center[0],
    lng: props.center[1],
    popupContent: "<b>北京天安门</b><br>中国首都的中心位置."
  });
  // 添加默认圆形
  addCircle(props.center, {
    popupContent: "天安门周边区域"
  });
  // 添加默认多边形
  addPolygon(
    [
      [39.91923, 116.387428],
      [39.92923, 116.397428],
      [39.91923, 116.407428]
    ],
    {
      popupContent: "这是一个多边形区域"
    }
  );
  // 添加点击事件
  handleMapClick(() => {
    console.log("地图被点击了");
  });
};

// 封装对外暴露的方法
defineExpose({
  // 设置地图中心点
  setCenter: latlng => {
    map.value.setView(latlng);
  },
  // 添加自定义标记
  addMarker: (latlng, popupContent) => {
    return addMarker({
      lat: latlng[0],
      lng: latlng[1],
      popupContent
    });
  }
});
</script>

<style scoped>
.map-container {
  margin: 0;
  padding: 0;
  width: 100vw;
  height: 100vh;
  display: flex;
  justify-content: center;
}
</style>
